package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.domain.Visit;
import cn.wolfcode.wolf2w.redis.service.IVisitRedisService;
import cn.wolfcode.wolf2w.repository.VisitRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.service.IVisitService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class VisitServiceImpl implements IVisitService {
    @Autowired
    private VisitRepository visitRepository;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IVisitRedisService visitRedisService;

    @Override
    public List<Visit> list() {
        List<Visit> all = visitRepository.findAll();
        return all;
    }


    @Override
    public Visit visit(String ownerId, UserInfo userInfo) {
        Optional<Visit> byWoId = visitRepository.findByWoId(ownerId);
        //判断是否有数据
        Visit visit = byWoId.orElse(null);
        if (visit==null){
           //数据库没有数据初始化
            visit=new Visit();
            UserInfo woUser = userInfoService.get(ownerId);
            BeanUtils.copyProperties(woUser, visit);
            //设置关联id
            visit.setWoId(ownerId);
        }
        //如果当前用户id为访客id,说明是自己的窝访问数不改变;
        if (ownerId.equals(userInfo.getId())){
            return null;
        }
        //否则进行添加操作
        List<UserInfo> visitors = visit.getVisitors();
        visitors.add(userInfo);
        //添加总访问量,和今日访问量
        visit.setTodayView(visit.getTodayView()+1);
        visit.setTotalView(visit.getTotalView()+1);
        //保存
        visitRepository.save(visit);

        return visit;
    }

    @Override
    public Visit getByOwnId(String id) {
        Visit visit = visitRepository.findByWoId(id).orElse(null);
        return visit;
    }
}
